import { _decorator, Sprite, Component, SpriteFrame, CCString } from "cc";
import { App } from "../../App";

const { ccclass, property, executeInEditMode, disallowMultiple, requireComponent, menu } = _decorator;

@ccclass
@executeInEditMode
@requireComponent(Sprite)
@disallowMultiple
@menu("i18n/Sprite")
export class i18nSprite extends Component {

    @property({ visible: false })
    private i18nString: string = "";

    onLoad() {
        App.i18n.register(this);
        this.reset();
    }

    @property({ type: CCString })
    get string() {
        return this.i18nString;
    }

    set string(value: string) {
        this.i18nString = value;
        const sprite:Sprite = this.getComponent(Sprite);
        if (App.isValid(sprite)){
            App.i18n.getSprite(value,(frame: SpriteFrame)=>{
                if (App.isValid(frame)){
                    sprite.spriteFrame = frame;
                }
            });
        }
    }

    public reset() {
        this.string = this.i18nString;
    }

    onDestroy() {
        App.i18n.unregister(this);
    }
}